package com.example.demo.test.l4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel channel = ServerSocketChannel.open();
        channel.configureBlocking(false);
        SelectionKey sscKey = channel.register(selector, SelectionKey.OP_ACCEPT);
        log.debug("sscKey:{}", sscKey);
        channel.bind(new InetSocketAddress(8080));
        while (true) {
            int count = selector.select();
            log.debug("select count: {}", count);
            // 获取所有事件
            Set<SelectionKey> keys = selector.selectedKeys();

            // 遍历所有事件，逐一处理
            Iterator<SelectionKey> iter = keys.iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
//                iter.remove();
                // 判断事件类型
                if (key.isAcceptable()) {
                    iter.remove();
                    ServerSocketChannel c = (ServerSocketChannel) key.channel();
                    // 必须处理
                    SocketChannel sc = c.accept();
                    sc.configureBlocking(false);
                    sc.register(selector, SelectionKey.OP_READ);
                    log.debug("连接已建立: {}", sc);
                    log.debug("key====>"+key);
                } else if (key.isReadable()) {
                    try {
                        SocketChannel sc = (SocketChannel) key.channel();
                        log.debug("可读: {}", sc);
                        log.debug("key====>"+key);
                        ByteBuffer buffer = ByteBuffer.allocate(4);
                        int read = sc.read(buffer);
                        if(read == -1) {
                            key.cancel();
                        } else {
                            buffer.flip();
                        }
                        Charset.defaultCharset().decode(buffer);

                    } catch (Exception e) {
                        key.channel();
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}